<template v-loading="loading">
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" v-show="showSearch" :inline="true">
      <el-form-item label="课程编号" prop="classCode">
        <el-input
          v-model="queryParams.classCode"
          placeholder="课程编号精确查询"
          clearable
          size="small"
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="课程名" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="课程名模糊查询"
          clearable
          size="small"
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="教师号" prop="tno" v-hasRole="['admin','root']">
          <el-input
          v-model="queryParams.tno"
          placeholder="教师号精确查询"
          clearable
          size="small"
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="教师姓名" prop="tname" v-hasRole="['admin','root']">
        <el-input
          v-model="queryParams.tname"
          placeholder="教师姓名模糊查询"
          clearable
          size="small"
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="courseList" @selection-change="handleSelectionChange" max-height="534">
      <el-table-column label="课程编号" prop="classCode" min-width="100" max-width="200"/>
      <el-table-column label="课程名" prop="name" :show-overflow-tooltip="true" min-width="150" max-width="300" />
      <el-table-column label="教师工号" prop="tno" :show-overflow-tooltip="true" min-width="150" max-width="300" />
      <el-table-column label="教师姓名" prop="tname" min-width="100" max-width="200" />
      <el-table-column label="出勤率" prop="percentage" min-width="100" max-width="200" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleUpdate(scope.row)"
          >详情</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改角色配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="88px">
        <h4>课程信息</h4>
        <el-row>
          <el-col :span="6">
            <el-form-item label="课程编号:" prop="classCode">
              <!-- <el-input  v-model="form.name"></el-input> -->
              {{form.classCode}}
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="课程名称:" prop="name">
              <!-- <el-input  v-model="form.name"></el-input> -->
              {{form.name}}
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="教师工号:" v-if="!checkRole(['admin','root','student'])">
              {{form.tno}}
            </el-form-item>
            <el-form-item label="教师工号:" prop="tno" v-hasRole="['admin','root']">
              <el-select v-model="form.checkedTeacher" value-key="userName" clearable placeholder="请输入教师工号" filterable remote :remote-method="remoteTeMethodUserName"
            :loading="loading" >
                <el-option
                  v-for="item in teacherOptions"
                  :key="item.userName"
                  :label="item.userName"
                  :value="item">
                  </el-option>
              </el-select>
              </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="教师姓名:"  v-if="!checkRole(['admin','root','student'])">
              {{form.tname}}
            </el-form-item>
            <el-form-item label="教师姓名:" prop="tname" v-hasRole="['admin','root']">
              <el-select v-model="form.checkedTeacher" value-key="userName" clearable placeholder="请输入教师姓名" filterable remote :remote-method="remoteTeMethodNickName"
            :loading="loading">
                <el-option
                  v-for="item in teacherOptions"
                  :key="item.userName"
                  :label="item.nickName"
                  :value="item">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <h4 style="position:relate">
          该课程学生信息
        </h4>
        <el-table :data="form.list" height="438">
          <el-table-column label="所属班级" prop="deptId" min-width="100" max-width="200">
            <template slot-scope="scope">
              {{deptDict[scope.row.deptId]}}
            </template>
          </el-table-column>
          <el-table-column label="学号" prop="userName" min-width="100" max-width="200"/>
          <el-table-column label="姓名" prop="nickName" min-width="100" max-width="200"/>
          <el-table-column label="考勤总次数" prop="count" min-width="80" max-width="200"/>
          <el-table-column label="签到次数" prop="ok" min-width="80" max-width="200"/>
          <el-table-column label="迟到次数" prop="late" min-width="80" max-width="200"/>
          <el-table-column label="早退次数" prop="leaveEarly" min-width="80" max-width="200"/>
          <el-table-column label="旷课次数" prop="truancy" min-width="80" max-width="200"/>
          <el-table-column label="出勤率" prop="percent" min-width="80" max-width="200"/>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" v-hasPermi="['basic:course:edit']">确 定</el-button>
        <el-button @click="cancel">关 闭</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { listCourse,listCourseStudent,listAllUser,updateCourse,listDept } from "@/api/basic/course";
// import { listRecord } from "@/api/basic/record";//用于查询考勤结果统计出勤率
import { checkPermi, checkRole } from "@/utils/permission"; // 权限判断函数

export default {
  name: "Course",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 课程表格数据
      courseList: [],
      //搜索出来的学生的数据
      studentOptions:[],
      //搜索出来的教师的数据
      teacherOptions:[],
      //所有学生的数据
      allStudentList:[],
      //所有教师的数据
      allTeacherList:[],
      //行政班级字典数据
      deptDict:{},
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      //选中的学生的参数
      checkedStudent:{},
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        classCode: undefined,
        name: undefined,
        tno: undefined,
        tname:undefined
      },
      // 表单参数
      form: {
        list:[],
        //选中的教师的参数
        checkedTeacher:{},
      },
      defaultProps: {
        children: "children",
        label: "label"
      },
      // 表单校验
      rules: {
        tno: [
          { required: true, message: "教师工号不能为空", trigger: "blur" }
        ],
        tname: [
          { required: true, message: "教师姓名不能为空", trigger: "blur" }
        ]
      }
    };
  },
  mounted() {
    this.getList();
    /**查询所有教师数据 */
    listAllUser({roleId:2}).then(
      response => {
        this.allTeacherList = response.data.list;
      }
    );
  },
  methods: {
    checkPermi,
    checkRole,
    /**进行教师数据搜索 */
    remoteTeMethodUserName(query) {
      /**防抖 */
      if (query !== '') {
        this.loading = true;
        setTimeout(() => {
          this.loading = false;
          //filter方法的目的是过滤
          this.teacherOptions = this.allTeacherList.filter(item => {
            return item.userName.toLowerCase()
              .indexOf(query.toLowerCase()) > -1;
          });
        }, 300);
      } else {
        this.teacherOptions = [];
      }
    },
    remoteTeMethodNickName(query) {
      /**防抖 */
      if (query !== '') {
        this.loading = true;
        setTimeout(() => {
          this.loading = false;
          //filter方法的目的是过滤
          this.teacherOptions = this.allTeacherList.filter(item => {
            return item.nickName.toLowerCase()
              .indexOf(query.toLowerCase()) > -1;
          });
        }, 300);
      } else {
        this.teacherOptions = [];
      }
    },
    /** 查询课程列表 */
    getList() {
      this.loading = true;
      listDept().then(response => {
          for (const iterator of response.data) {
            this.deptDict[iterator.deptId] = iterator.deptName;
          }
      });
      listCourse(this.queryParams).then( response => {
          this.courseList = response.data.list;
          for (const iterator of this.courseList) {
            iterator.percentage = (Number(iterator.percentage)*100).toFixed(2) + '%';
            // console.log(Number(iterator.percentage)*100);
          }
          this.total = response.data.total;
          this.loading = false;
        })
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      if (this.$refs.menu != undefined) {
        this.$refs.menu.setCheckedKeys([]);
      }
      this.form = {
        classCode: undefined,
        name:undefined,
        tno:undefined,
        tname:undefined,
        list:[],
        checkedTeacher:{}
      };
      this.teacherOptions = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.classCode)
      this.single = selection.length!=1
      this.multiple = !selection.length
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.loading = true;
      [this.form.classCode,this.form.name,this.form.tno,this.form.tname] = [row.classCode,row.name,row.tno,row.tname];
      const classCode = row.classCode;
      this.form.checkedTeacher.userName = this.form.tno;
      this.form.checkedTeacher.nickName = this.form.tname;
      this.teacherOptions.push({userName:this.form.tno,nickName:this.form.tname})
      listCourseStudent({classCode:classCode}).then(response => {
        this.form.list = response.data.list;
        this.open = true;
        this.title = "课程详细信息";
        this.loading = false;
      });
    
    },
    /** 提交按钮 */
    submitForm: function() {
      this.form.tno = this.form.checkedTeacher.userName;
      this.form.tname = this.form.checkedTeacher.nickName;
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.classCode != undefined) {
            this.form.list = undefined;
            updateCourse(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } 
        }
      });
    },  
  }
};
</script>